package cn.xlbweb.cli.service.impl;

import cn.xlbweb.cli.repository.UserRepository;
import cn.xlbweb.cli.pojo.jdo.UserDO;
import cn.xlbweb.cli.pojo.dto.LoginDTO;
import cn.xlbweb.cli.service.LoginService;
import cn.xlbweb.ji.JwtUtils;
import cn.xlbweb.util.response.ServerResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

/**
 * @author: bobi
 * @date: 2021/1/31 下午10:17
 * @description:
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public ServerResponse login(LoginDTO dto) {
        String md5Password = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        UserDO userDO = userRepository.findByUsernameAndPassword(dto.getUsername(), md5Password);
        if (Objects.nonNull(userDO)) {
            // 约定: 账号-角色名 (jack-manager)
            String userInfo = StringUtils.join(userDO.getUsername(), "-", userDO.getRole().getRoleName());
            return ServerResponse.success("登录成功", JwtUtils.encrypt(userInfo));
        }
        return ServerResponse.error("登录失败，账号或密码错误");
    }
}
